import type { PlayerConfigOptions } from 'svga/dist/types'
import { useEffect, useRef } from 'react'
import { Parser, Player } from 'svga'

export default function useSvga(
  svgaPath: string,
  config?: PlayerConfigOptions,
) {
  const player = useRef<Player>()
  const parser = useRef<Parser>(
    new Parser({
      isDisableImageBitmapShim: true,
    }),
  )

  async function initSvga(container: HTMLCanvasElement) {
    const svga = await parser.current.load(svgaPath)
    player.current = new Player({
      container,
      isCacheFrames: true,
      isUseIntersectionObserver: true,
      isOpenNoExecutionDelay: true,
      ...config,
    })

    return await player.current.mount(svga)
  }

  useEffect(() => {
    return () => {
      player.current?.destroy()
    }
  }, [])

  return {
    init: initSvga,
    player,
  }
}
